﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Hrm.Core;
using Hrm.EntityFramework;
using Hrm.Web.Framework;
using Hrm.Services;
using Newtonsoft.Json;

namespace Hrm.Web.Areas.Permissions.Controllers
{
    [RoleAuthorize]
    public class RolesController : Controller
    {
        IRoleService _roleService;
        IUserService _userService;
        IApplicationService _applicationService;
        IResourceAndPermissionService _resourceAndPermissionService;
        ICacheManager _cacheManager;

        public RolesController(IRoleService roleService, IUserService userService, IApplicationService applicationService, IResourceAndPermissionService resourceAndPermissionService, ICacheManager cacheManager)
        {
            this._roleService = roleService;
            this._userService = userService;
            this._applicationService = applicationService;
            this._resourceAndPermissionService = resourceAndPermissionService;
            this._cacheManager=cacheManager;
        }

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult PageRoles(PageRequest<RoleDto> request)
        {
            var result = _roleService.GetPageList(request);
            return Json(result);
        }

        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Role role = _roleService.GetById(id);
            if (role == null)
            {
                return HttpNotFound();
            }
            return View(role);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Role role)
        {
            if (ModelState.IsValid)
            {
                this._roleService.Insert(role);
                return RedirectToAction("Index");
            }

            return View(role);
        }

        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Role role = _roleService.GetById(id);
            if (role == null)
            {
                return HttpNotFound();
            }
            return View(role);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,Description")] Role role)
        {
            if (ModelState.IsValid)
            {
                var model = this._roleService.GetById(role.Id);
                if (TryUpdateModel(model, "", new string[] { "Code", "Name", "Description" }))
                    this._roleService.Update(role);
                return RedirectToAction("Index");
            }
            return View(role);
        }

        [HttpPost]
        public JsonResult Delete(int id)
        {
            ResponseModel result = new ResponseModel();
            if (id == 0)
            {
                result.SetFailed("删除失败，参数不能为空！");
                return Json(result);
            }
            Role resource = this._roleService.GetById(id);
            if (resource == null)
            {
                result.SetFailed("删除失败，查询没有改数据！");
                return Json(result);
            }
            this._roleService.UpdateDisabled(resource);
            return Json(result);
        }

        public ActionResult AllocateUsers(int id)
        {
            var model = this._roleService.GetById(id);
            ViewBag.RoleId = id;
            ViewBag.UserIds = JsonConvert.SerializeObject(model.Users == null ? new List<int>() : model.Users.Select(p => p.Id).ToList());
            return View();
        }

        [HttpPost]
        public JsonResult AllocateUsersSubmit(AllocateUsersDto request)
        {
            var result = new ResponseModel();
            var selectUserIds = request.SelectUserIds ?? new List<int>();
            var userIds = request.UserIds ?? new List<int>();
            var deleteUserIds = userIds.Where(p => !selectUserIds.Contains(p)).ToList();
            var addUserIds = selectUserIds.Where(p => !userIds.Contains(p)).ToList();
            var model = this._roleService.GetById(request.RoleId);
            try
            {
                if (model.Users == null)
                {
                    model.Users = new List<User>();
                }
                else
                {
                    var DeleteUsers = this._userService.GetList(p => deleteUserIds.Contains(p.Id)).ToList();
                    DeleteUsers.ForEach(p => model.Users.Remove(p));
                }
                var addUser = this._userService.GetList(p => addUserIds.Contains(p.Id)).ToList();
                addUser.ForEach(p => model.Users.Add(p));
                this._roleService.Update(model);
            }
            catch (Exception ex)
            {
                result.SetFailed("操作失败：" + ex.Message);
            }

            return Json(result);
        }

        public ViewResult ResourcePermission(int id)
        {
            var app = this._applicationService.GetApplications();
            ViewBag.RoleId = id;
            return View(app);
        }

        [HttpPost]
        public JsonResult ResourcePermissionSubmit(List<ResourcePermissionTreeNodeDto> list, int roleId)
        {
            var result = new ResponseModel();
            var model = this._roleService.GetById(roleId);
            try
            {
                foreach (var item in list)
                {
                    if (item.Type == "Permission")
                    {
                        var temp = this._resourceAndPermissionService.GetList(p => p.Id.ToString() == item.Id && p.Resource.Code == item.PId).First();
                        if (item.Check)
                        {
                            if (model.ResourceAndPermissions == null)
                                model.ResourceAndPermissions = new List<ResourceAndPermission>();
                            model.ResourceAndPermissions.Add(temp);
                        }
                        else
                        {
                            model.ResourceAndPermissions.Remove(temp);
                        }
                    }
                }
                this._roleService.Update(model);
                this._cacheManager.Clear();
            }
            catch (Exception ex)
            {
                result.SetFailed("操作失败：" + ex.Message);
            }

            return Json(result);
        }

        public JsonResult ResourcePermissionData(int appId, int roleId)
        {
            var data = this._roleService.ResourcePermissionData(appId, roleId);
            return Json(data);
        }
    }
}
